package com.netmi.myuploadfileretrofit.http;

import com.netmi.myuploadfileretrofit.inteface.ReqProgressCallBack;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 类描述：拦截器 主要添加Tooken与
 * 创建人：tgw
 * 创建时间：2020/7/28
 * 修改备注：
 */
public class HttpReqeustInterceptor implements Interceptor {


    /**
     * synchronized 加入同步，避免多线程进入，产生线程同步问题：多次刷新token，token数据出错
     */

    private ReqProgressCallBack callBack;
    private String token;

    public HttpReqeustInterceptor(ReqProgressCallBack callBack,String token) {
        this.callBack = callBack;
        this.token = token;
    }

    @Override
    public synchronized Response intercept(Chain chain) throws IOException {
//        Request request = chain.request();
//
//        if(null == request.body()){
//            return chain.proceed(request);
//        }
//
//        Request build = request.newBuilder()
//                .method(request.method(),
//                        new ProgressResponseBody(request.body(),
//                                callBack))
//                .build();
//        return chain.proceed(build);


        Request request = chain.request();
        Request.Builder requestBuilder = request.newBuilder();
        requestBuilder.addHeader("token", token);
        if (null == request.body()) {
            return chain.proceed(request);
        }

        //添加文件上传进度监听
        requestBuilder.method(request.method(),
                new ProgressResponseBody(request.body(),
                        callBack));

        request = requestBuilder.build();

        Response response = chain.proceed(request);

        return response;
    }

}
